<template>
  <view class="container">
    <!-- 提示信息 -->
    <view class="notice-area">
      <text class="notice-text">目前只能多个图生成一个报销，无法一个图生成多个报销。</text>
    </view>

    <!-- 配置区域 -->
    <view class="config-area">
      <button class="navigate-btn" @click="goToTemplate">模板管理</button>
      <button class="navigate-btn" @click="goToExtraRules">额外规则</button>
      <button class="clear-btn" @click="clearAll">清空数据</button>
      <button class="process-all-btn" @click="recognizeAllGroups">识别所有组</button>
    </view>

    <!-- 操作区域 -->
    <view class="operation-area">

      <!-- 分组容器 -->
      <view class="group-container">
        <view v-for="(group, groupIndex) in groups" :key="group.id" class="group-box">
          <text class="group-title">第 {{ groupIndex + 1 }} 组</text>

          <!-- 为本组选图按钮 -->
          <button class="choose-btn" @click="chooseImages(group.id)">为本组选图</button>

          <picker mode="selector" range-key="templateName" :range="templates" @change="onTemplateChange($event, group.id)" class="template-picker">
            <view class="picker-text">{{ getTemplateName(group.templateId) }}</view>
          </picker>

          <view class="image-preview-container">
            <view
              v-for="(img, imgIndex) in group.images"
              :key="img.path"
              class="image-item"
              draggable="true"
              @dragstart="dragStart(group.id, imgIndex)"
              @dragover.prevent
              @drop="drop(group.id, imgIndex)"
              @click="previewImage(img.src)"
            >
              <image :src="img.src" mode="aspectFill" class="preview-image"></image>
              <text class="delete-icon" @click.stop="removeImage(group.id, imgIndex)">×</text>
            </view>
          </view>

          <button class="process-btn" @click="recognizeGroup(group.id)">识别本组</button>

          <!-- 结果展示区域 -->
          <view v-if="group.result.length > 0" class="result-area">
            <block v-for="(item, index) in group.result.split('\n')" :key="index">
              <text class="result-line">{{ item }}</text>
            </block>
            <button class="copy-btn" @tap="copyResult(group.result)">复制本组结果</button>
          </view>
        </view>

        <!-- 新增分组按钮 -->
        <view class="add-group" @click="addGroup">+ 新增分组</view>
      </view>
    </view>

    <!-- 图片预览 -->
    <view v-if="showPreview" class="preview-modal" @click="closePreview">
      <image :src="previewImageUrl" mode="widthFix" class="preview-full-image"></image>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      // 分组数据
      groups: [
        { id: Date.now(), images: [], templateId: null, result: '' }
      ],
      dragging: null,
      showPreview: false,
      previewImageUrl: '',

      // 模板与规则
      templates: [],
      rules: []
    };
  },
  mounted() {
    this.fetchTemplates();
    this.fetchRules();
  },
  methods: {
    // 页面跳转
    goToTemplate() {
      uni.navigateTo({ url: '/pages/intelligent/TemplateManage' });
    },
    goToExtraRules() {
      uni.navigateTo({ url: '/pages/intelligent/ExtraRulesList' });
    },

    // 图片上传 - 修改为传入 groupId
    chooseImages(groupId) {
      uni.chooseMessageFile({
        count: 9,
        type: 'image',
        success: (res) => {
          const newFiles = res.tempFiles.map(file => ({
            path: file.path,
            src: file.path
          }));
          const group = this.groups.find(g => g.id === groupId);
          if (group) {
            group.images.push(...newFiles);
          }
        },
        fail: () => uni.showToast({ title: '选择失败', icon: 'none' })
      });
    },

    // 分组操作
    addGroup() {
      this.groups.push({ id: Date.now(), images: [], templateId: null, result: '' });
    },
    removeImage(groupId, imgIndex) {
      const group = this.groups.find(g => g.id === groupId);
      if (group) {
        group.images.splice(imgIndex, 1);
      }
    },
    dragStart(groupId, imgIndex) {
      this.dragging = { groupId, imgIndex };
    },
    drop(targetGroupId, targetIndex) {
      if (!this.dragging) return;
      const fromGroup = this.groups.find(g => g.id === this.dragging.groupId);
      const toGroup = this.groups.find(g => g.id === targetGroupId);

      if (fromGroup && toGroup) {
        const [movedImg] = fromGroup.images.splice(this.dragging.imgIndex, 1);
        toGroup.images.splice(targetIndex, 0, movedImg);
      }
      this.dragging = null;
    },

    // 模板选择
    onTemplateChange(e, groupId) {
      const selectedIdx = e.detail.value;
      const selectedTemplate = this.templates[selectedIdx];
      const group = this.groups.find(g => g.id === groupId);
      if (group) {
        group.templateId = selectedTemplate.templateId;
      }
    },
    getTemplateName(id) {
      const temp = this.templates.find(t => t.templateId === id);
      return temp ? temp.templateName : '请选择模板';
    },

    // 获取模板与规则
    async fetchTemplates() {
      try {
        const res = await uni.request({
          url: 'http://localhost:8083/template',
          method: 'GET'
        });
        this.templates = res.data;
      } catch (err) {
        uni.showToast({ title: '没连上后台你个笨蛋', icon: 'none' });
      }
    },
    async fetchRules() {
      try {
        const res = await uni.request({
          url: 'http://localhost:8083/rules',
          method: 'GET'
        });
        this.rules = res.data;
      } catch (err) {
        uni.showToast({ title: '没连上后台你个笨蛋', icon: 'none' });
      }
    },

    // 识别一组
    async recognizeGroup(groupId) {
      const group = this.groups.find(g => g.id === groupId);
      if (!group || group.images.length === 0) {
        uni.showToast({ title: '请先添加图片', icon: 'none' });
        return;
      }

      uni.showLoading({ title: '识别中' });

      let mergeText = '';
      for (const image of group.images) {
        try {
          const ocrResult = await this.uploadImageAndGetOCR(image.path);
          mergeText += ocrResult + '; ';
        } catch (err) {
          uni.showToast({ title: '识别失败', icon: 'none' });
        }
      }

      uni.hideLoading();

      // 应用模板和规则
      const template = this.templates.find(t => t.templateId === group.templateId);
      const rule = this.rules.find(r => r.templateId === group.templateId);

      if (!template) {
        uni.showToast({ title: '未选择模板', icon: 'none' });
        return;
      }

      const requestData = {
        text: mergeText,
        instruction: `以上这一段话中，帮我总结出一段信息，严格按照格式来回复，格式如下示例：${template.templateContent}。${rule?.ruleString || ''}`,
      };

      uni.showLoading({ title: '生成结构化内容' });
      try {
        const res = await uni.request({
          url: 'http://localhost:8083/api/get-result',
          method: 'POST',
          data: requestData
        });
        group.result = res.data.replace(/[$$\（\）\。]/g, ''); // 将结果写入当前组的 result 字段
        uni.hideLoading();
        uni.showToast({ title: '转换完成' });
      } catch (err) {
        uni.showToast({ title: '转换失败', icon: 'none' });
      }
    },

    uploadImageAndGetOCR(filePath) {
      return new Promise((resolve, reject) => {
        uni.uploadFile({
          url: 'http://localhost:8083/api/process-image',
          filePath: filePath,
          name: 'file',
          success: (uploadRes) => {
            try {
              const data = JSON.parse(uploadRes.data);
              resolve(data.content);
            } catch (e) {
              reject('解析失败');
            }
          },
          fail: (err) => {
            reject(err);
          }
        });
      });
    },

    // 识别所有组
    recognizeAllGroups() {
      this.groups.forEach(group => {
        if (group.images.length === 0 || !group.templateId) {
          uni.showToast({ title: '请确保每个组都已选择图片和模板', icon: 'none' });
          return;
        }
        this.recognizeGroup(group.id);
      });
    },

    // 清空所有
    clearAll() {
      this.groups = [{ id: Date.now(), images: [], templateId: null, result: '' }];
    },

    // 复制结果
    copyResult(result) {
      uni.setClipboardData({
        data: result,
        success: () => {
          uni.showToast({ title: '复制成功' });
        }
      });
    },

    // 图片预览
    previewImage(src) {
      this.previewImageUrl = src;
      this.showPreview = true;
    },
    closePreview() {
      this.showPreview = false;
    }
  }
};
</script>

<style lang="scss">
.container {
  padding: 20rpx;
}

.notice-area {
  margin-bottom: 40rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  height: 80rpx;
  background-color: #ffeb3b;
  border-radius: 12rpx;
}

.notice-text {
  font-size: 28rpx;
  color: #333;
  font-weight: bold;
}

.config-area {
  margin-bottom: 40rpx;
  display: flex;
  flex-wrap: wrap;
  gap: 20rpx;
}

.navigate-btn, .clear-btn, .choose-btn, .process-btn, .copy-btn, .process-all-btn {
  width: 180rpx;
  height: 80rpx;
  background-color: #07c160;
  color: white;
  font-size: 26rpx;
  border-radius: 8rpx;
  text-align: center;
  line-height: 80rpx;
}

.clear-btn {
  background-color: #e64340;
}

.process-all-btn {
  background-color: #5ac8fa;
}

.choose-btn {
  margin-bottom: 30rpx;
}

.group-container {
  display: flex;
  flex-direction: column;
  gap: 30rpx;
}

.group-box {
  padding: 20rpx;
  background-color: #fff;
  border: 1rpx solid #eee;
  border-radius: 12rpx;
}

.group-title {
  font-weight: bold;
  margin-bottom: 20rpx;
}

.template-picker {
  margin-bottom: 20rpx;
  padding: 10rpx;
  border: 1rpx solid #ccc;
  border-radius: 8rpx;
  color: #333;
}

.picker-text {
  font-size: 26rpx;
  color: #555;
}

.image-preview-container {
  display: flex;
  flex-wrap: wrap;
  gap: 20rpx;
}

.image-item {
  position: relative;
  width: 160rpx;
  height: 160rpx;
  border-radius: 12rpx;
  overflow: hidden;
  box-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.1);
}

.preview-image {
  width: 100%;
  height: 100%;
}

.delete-icon {
  position: absolute;
  top: -10rpx;
  right: -10rpx;
  color: white;
  background-color: rgba(0, 0, 0, 0.5);
  width: 40rpx;
  height: 40rpx;
  text-align: center;
  line-height: 40rpx;
  border-radius: 50%;
  font-size: 28rpx;
}

.add-group {
  width: 100%;
  height: 100rpx;
  border: 2rpx dashed #aaa;
  border-radius: 12rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 28rpx;
  color: #888;
}

.result-area {
  margin-top: 40rpx;
  padding: 20rpx;
  background-color: #f9f9f9;
  border-radius: 12rpx;
}

.result-line {
  display: block;
  margin-bottom: 20rpx;
  font-size: 28rpx;
}

.copy-btn {
  width: 100%;
  height: 80rpx;
  background-color: #07c160;
  color: white;
  font-size: 26rpx;
  border-radius: 8rpx;
  text-align: center;
  line-height: 80rpx;
}

.preview-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.8);
  display: flex;
  justify-content: center;
  align-items: center;
}

.preview-full-image {
  max-width: 100%;
  max-height: 100%;
}
</style>